package com.redisexample;

import org.springframework.beans.BeansException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import com.redisexample.domain.User;
import com.redisexample.utils.RedisUtil;

/**
 * 基于SpringBoot2.0 + spring-boot-starter-data-redis搭建的工程，
 * 附带一个多功能工具类，并且 自定义统一RedisTemplate序列化机制
 * 首先安装redis ，此项目对应redis版本为3.x 修改redis为允许远程主机访问，然后启动redis 然后就可以操作
 * @author CJ
 */
@SpringBootApplication
public class Application implements ApplicationContextAware {

	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		Application.applicationContext = applicationContext;
	}

	@SuppressWarnings("unchecked")
	public static <T> T getBean(String beanName) {
		assertApplicationContext();
		return (T) applicationContext.getBean(beanName);
	}

	public static <T> T getBean(Class<T> requiredType) {
		assertApplicationContext();
		return applicationContext.getBean(requiredType);
	}

	private static void assertApplicationContext() {
		if (Application.applicationContext == null) {
			throw new RuntimeException("applicaitonContext属性为null,请检查是否注入了SpringContext!");
		}
	}

	public static void main(String[] args) {
			SpringApplication.run(Application.class, args);
			assertApplicationContext();
			RedisUtil redisUtil = applicationContext.getBean(RedisUtil.class);
			
			//判断key是否存在
			System.out.println("存在【myname】的key吗"+redisUtil.hasKey("myname"));
			
			//put一个对象进去
			System.out.println(redisUtil.set("user1", new User("cj", 625)));
			
			//get出一个对象
			User user = (User)redisUtil.get("user1");
			System.out.println(user.getUsername());
			System.out.println(user.getAge());
			
			//更多功能详见RedisUtil工具类
			//.......
	}

}
